package com.xmtlxx.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class WordUtil {
    private static Configuration configuration = null;
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(WordUtil.class, "/templates");
    }

    public WordUtil() {
        throw new AssertionError();
    }

    /**
     * 以下载的方式生成word，自定义路径
     *
     * @param dataMap
     */
    public static void createWord(String templateName, Map<String, Object> dataMap, String filePath) {

        // 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
        // ftl文件存放路径
        configuration.setClassForTemplateLoading(WordUtil.class, "/template");
        Template t;
        try {
            // 2.ftl为要装载的模板
            t = configuration.getTemplate(templateName);
            File file=new File(filePath);
            FileWriter fileWriter=new FileWriter(file);
            t.process(dataMap, fileWriter);
            fileWriter.close();
            // 由于ftl模板生成的文件实质上还是xml文件 , 所以有需要的还要转换一下格式
        } catch (TemplateException | IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("deptName", "沙县公安局刑事侦查大队五中队");
        map.put("orderNo", "R20230115221056");
        map.put("takeTime", DateUtils.date2String(new Date(),"yyyy年MM月dd日 HH时mm分"));
        map.put("taker", "陈荣瑜");
        map.put("takeTel", "13599518139");
        map.put("takeAddr", "福建省厦门市集美区软件园三期B13栋701-3A");
        map.put("arriveTime", DateUtils.date2String(new Date(),"yyyy年MM月dd日 HH时mm分"));
        map.put("receive", "陈荣瑜");
        map.put("receiveTel", "13599518139");
        map.put("receiveAddr", "福建省厦门市集美区软件园三期B13栋701-3A");

        List<Map<String,Object>> items = new ArrayList<>();
        for(int i=1;i<= 15;i++){
            Map<String,Object> item = new HashMap<>();
            item.put("index",i);
            item.put("name","物品名称"+i);
            item.put("pno","W3505813890000000"+i);
            item.put("box","B"+i);
            item.put("nums",i);
            item.put("unit","件");
            item.put("way","干燥柜");
            items.add(item);
        }
        map.put("items",items);
        createWord("takeTmpl.ftl",map,"takeWord.docx");
    }
}

